package com.example.module01.controller;

import com.example.module01.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     *
     * @return
     */
    @GetMapping("/getRedisInfo")
    public String getRedisInfo(){
        System.out.println(redisTemplate == null);
        // 插入一条string类型数据，空指正异常
        redisTemplate.opsForValue().set("name", "李四");
        // 读取一条string类型数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name = " + name);
        User user = new User("虎哥", 18);
        redisTemplate.opsForValue().set("user:100", user);
        return name.toString();

    }

    /**
     * 将对象序列化和反序列化
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/getStringRedisInfo")
    public String getStringRedisInfo() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        // 准备对象
        User user = new User("虎哥", 18);
        // 手动序列化
        String json = mapper.writeValueAsString(user);
        // 写入一条数据到redis
        stringRedisTemplate.opsForValue().set("user:200", json);

        // 读取数据
        String val = stringRedisTemplate.opsForValue().get("user:200");
        // 反序列化
        User user1 = mapper.readValue(val, User.class);
        return json;
    }

}
